package com.wmyg.antifake.controller;

import com.wmyg.antifake.entity.Product;
import com.wmyg.antifake.entity.ProductOrigin;
import com.wmyg.antifake.service.ProductService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.List;

/**
 * @author 王卓逸
 * @program TODO
 * @description TODO
 * @create 2019-05-20
 */
@RestController
@RequestMapping(value = "/product")
public class ProductController {

    @Autowired
    ProductService productService;

    @PreAuthorize("hasAuthority('addproduct')")
    @PostMapping(value = "/product")
    public Boolean saveProduct(Product product, @RequestParam(value = "origins") String[] origins, Principal principal) {
        for (String o :
                origins) {
            ProductOrigin origin = new ProductOrigin();
            origin.setOriginInfo(o);
            product.getProductOrigins().add(origin);
        }
        return productService.saveProduct(product, principal.getName());
    }

    @PreAuthorize("hasAuthority('createcode')")
    @GetMapping(value = "/products")
    public List<Product> getProductList(Principal principal) {
        return productService.getProductList(principal.getName());
    }

    @PreAuthorize("hasAuthority('product')")
    @GetMapping(value = "/productpage")
    public Page<Product> getProductPage(Principal principal, Integer index, String query) {
        if (StringUtils.isBlank(query)) {
            return productService.getProductPage(principal.getName(), index);
        } else {
            return productService.getProductPage(principal.getName(), index, query);
        }
    }

    @PreAuthorize("hasAuthority('addproduct') or hasAuthority('product')")
    @PutMapping(value = "/product")
    public Boolean updateProduct(Product product, @RequestParam(value = "origins") String[] origins, Principal principal) {
        for (String o :
                origins) {
            ProductOrigin origin = new ProductOrigin();
            origin.setOriginInfo(o);
            product.getProductOrigins().add(origin);
        }
        return productService.saveProduct(product, principal.getName());
    }

    @PreAuthorize("hasAuthority('addproduct') or hasAuthority('product')")
    @GetMapping(value = "/product")
    public Product getProduct(String productId) {
        return productService.findByProductId(productId);
    }

}
